<template>
  <div class="debug-view min-h-screen bg-gray-100 p-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="header mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-4">JSONL编辑器调试页面</h1>
        <p class="text-gray-600">用于测试和调试ScriptVue项目的核心功能</p>
      </div>

      <!-- 调试步骤卡片 -->
      <div class="grid gap-6 mb-8">
        <!-- 步骤1: 基础功能测试 -->
        <div class="debug-card bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center mb-4">
            <div class="w-8 h-8 bg-blue-500 text-white rounded-full flex items-center justify-center font-bold mr-3">
              1
            </div>
            <h2 class="text-xl font-semibold text-gray-800">基础功能测试</h2>
          </div>
          
          <div class="space-y-3">
            <el-button
              type="primary"
              @click="testBasicFunctions"
              :loading="testStates.basic"
              class="mr-3"
            >
              <el-icon class="mr-2"><i-ep-cpu /></el-icon>
              测试基础功能
            </el-button>
            
            <div v-if="testResults.basic" class="result-display">
              <el-alert
                :title="testResults.basic.title"
                :type="testResults.basic.type"
                :description="testResults.basic.description"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>

        <!-- 步骤2: 脚本导入测试 -->
        <div class="debug-card bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center mb-4">
            <div class="w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center font-bold mr-3">
              2
            </div>
            <h2 class="text-xl font-semibold text-gray-800">脚本导入测试</h2>
          </div>
          
          <div class="space-y-3">
            <div class="flex gap-3">
              <el-button
                type="success"
                @click="testPlaywrightImport"
                :loading="testStates.playwright"
              >
                <el-icon class="mr-2"><i-ep-upload /></el-icon>
                测试Playwright导入
              </el-button>
              
              <el-button
                type="success"
                @click="testJsonlImport"
                :loading="testStates.jsonl"
              >
                <el-icon class="mr-2"><i-ep-document /></el-icon>
                测试JSONL导入
              </el-button>
            </div>
            
            <div v-if="testResults.import" class="result-display">
              <el-alert
                :title="testResults.import.title"
                :type="testResults.import.type"
                :description="testResults.import.description"
                show-icon
                :closable="false"
              />
              
              <!-- 显示导入的步骤 -->
              <div v-if="importedSteps.length > 0" class="mt-4">
                <h4 class="text-sm font-medium text-gray-700 mb-2">导入的步骤 ({{ importedSteps.length }} 个):</h4>
                <div class="space-y-2 max-h-40 overflow-y-auto">
                  <div
                    v-for="step in importedSteps"
                    :key="step.stepNumber"
                    class="text-xs p-2 bg-gray-50 rounded border-l-4 border-blue-400"
                  >
                    <div class="font-medium">步骤 {{ step.stepNumber }}: {{ step.description }}</div>
                    <div class="text-gray-600">{{ step.type }} - {{ step.action }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤3: 状态管理测试 -->
        <div class="debug-card bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center mb-4">
            <div class="w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center font-bold mr-3">
              3
            </div>
            <h2 class="text-xl font-semibold text-gray-800">状态管理测试</h2>
          </div>
          
          <div class="space-y-3">
            <el-button
              type="info"
              @click="testStoreIntegration"
              :loading="testStates.store"
            >
              <el-icon class="mr-2"><i-ep-coin /></el-icon>
              测试Pinia Store
            </el-button>
            
            <div v-if="testResults.store" class="result-display">
              <el-alert
                :title="testResults.store.title"
                :type="testResults.store.type"
                :description="testResults.store.description"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>

        <!-- 步骤4: 完整流程测试 -->
        <div class="debug-card bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center mb-4">
            <div class="w-8 h-8 bg-red-500 text-white rounded-full flex items-center justify-center font-bold mr-3">
              4
            </div>
            <h2 class="text-xl font-semibold text-gray-800">完整流程测试</h2>
          </div>
          
          <div class="space-y-3">
            <el-button
              type="danger"
              @click="testCompleteWorkflow"
              :loading="testStates.workflow"
            >
              <el-icon class="mr-2"><i-ep-connection /></el-icon>
              运行完整测试
            </el-button>
            
            <div v-if="testResults.workflow" class="result-display">
              <el-alert
                :title="testResults.workflow.title"
                :type="testResults.workflow.type"
                :description="testResults.workflow.description"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 控制台命令 -->
      <div class="console-section bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-xl font-semibold text-gray-700 mb-4 flex items-center">
          <el-icon class="mr-2"><i-ep-monitor /></el-icon>
          控制台命令
        </h2>
        <div class="bg-gray-900 text-green-400 p-4 rounded font-mono text-sm">
          <div class="mb-2 text-yellow-400"># 在浏览器控制台中运行以下命令:</div>
          <div class="mb-2">
            <span class="text-blue-400">// 检查Vue应用状态</span>
          </div>
          <div class="mb-2">window.__VUE_DEVTOOLS_GLOBAL_HOOK__</div>
          <div class="mb-2">
            <span class="text-blue-400">// 访问Pinia stores</span>
          </div>
          <div class="mb-2">app.config.globalProperties.$pinia</div>
          <div class="text-gray-400 text-xs mt-3">提示: 打开开发者工具查看更多调试信息</div>
        </div>
      </div>

      <!-- 调试日志 -->
      <div class="log-section bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-xl font-semibold text-gray-700 flex items-center">
            <el-icon class="mr-2"><i-ep-document /></el-icon>
            调试日志
          </h2>
          <el-button size="small" @click="clearLogs">
            <el-icon class="mr-1"><i-ep-delete /></el-icon>
            清空日志
          </el-button>
        </div>
        
        <div class="log-container bg-gray-50 p-4 rounded border max-h-96 overflow-y-auto font-mono text-sm">
          <div v-if="debugLogs.length === 0" class="text-gray-500 text-center py-4">
            暂无调试日志
          </div>
          <div
            v-for="(log, index) in debugLogs"
            :key="index"
            class="log-entry mb-1"
            :class="getLogClass(log.type)"
          >
            <span class="log-timestamp text-gray-500">[{{ log.timestamp }}]</span>
            <span class="log-level font-medium mx-2">{{ log.type.toUpperCase() }}:</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useScriptStore } from '../stores/script'
import { useRecordingStore } from '../stores/recording'
import { useExecutionStore } from '../stores/execution'
import { ElMessage } from 'element-plus'

// Element Plus 图标
import {
  Cpu as iEpCpu,
  Upload as iEpUpload,
  Document as iEpDocument,
  Coin as iEpCoin,
  Connection as iEpConnection,
  Monitor as iEpMonitor,
  Delete as iEpDelete
} from '@element-plus/icons-vue'

// Stores
const scriptStore = useScriptStore()
const recordingStore = useRecordingStore()
const executionStore = useExecutionStore()

// 响应式数据
const testStates = ref({
  basic: false,
  playwright: false,
  jsonl: false,
  store: false,
  workflow: false
})

const testResults = ref({
  basic: null,
  import: null,
  store: null,
  workflow: null
})

const importedSteps = ref([])
const debugLogs = ref([])

// 测试数据
const playwrightTestScript = `import { test, expect } from '@playwright/test';

test('登录测试', async ({ page }) => {
  await page.goto('https://example.com/login');
  await page.fill('#username', 'admin');
  await page.fill('#password', 'password123');
  await page.click('#login-button');
  await expect(page.locator('.welcome-message')).toBeVisible();
});`

const jsonlTestScript = `{"stepNumber":1,"type":"navigation","action":"goto","description":"打开登录页面","url":"https://example.com/login","timestamp":"2024-01-01T10:00:00Z"}
{"stepNumber":2,"type":"input","action":"fill","description":"输入用户名","selector":"#username","value":"admin","timestamp":"2024-01-01T10:00:01Z"}
{"stepNumber":3,"type":"input","action":"fill","description":"输入密码","selector":"#password","value":"password123","timestamp":"2024-01-01T10:00:02Z"}
{"stepNumber":4,"type":"click","action":"click","description":"点击登录按钮","selector":"#login-button","timestamp":"2024-01-01T10:00:03Z"}`

// 方法
const addLog = (message, type = 'info') => {
  debugLogs.value.push({
    timestamp: new Date().toLocaleTimeString(),
    type,
    message
  })
  
  // 自动滚动到底部
  setTimeout(() => {
    const logContainer = document.querySelector('.log-container')
    if (logContainer) {
      logContainer.scrollTop = logContainer.scrollHeight
    }
  }, 100)
}

const testBasicFunctions = async () => {
  testStates.value.basic = true
  addLog('开始基础功能测试', 'info')

  try {
    // 测试Vue应用是否正常运行
    addLog('检查Vue应用状态...', 'info')
    
    // 测试路由
    addLog('测试路由系统...', 'info')
    
    // 测试组件渲染
    addLog('测试组件渲染...', 'info')
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    testResults.value.basic = {
      title: '基础功能测试通过',
      type: 'success',
      description: 'Vue应用、路由系统、组件渲染均正常工作'
    }
    
    addLog('基础功能测试完成', 'success')
    ElMessage.success('基础功能测试通过')
  } catch (error) {
    testResults.value.basic = {
      title: '基础功能测试失败',
      type: 'error',
      description: `测试失败: ${error.message}`
    }
    
    addLog(`基础功能测试失败: ${error.message}`, 'error')
    ElMessage.error('基础功能测试失败')
  } finally {
    testStates.value.basic = false
  }
}

const testPlaywrightImport = async () => {
  testStates.value.playwright = true
  addLog('开始Playwright脚本导入测试', 'info')

  try {
    const result = scriptStore.importScript(playwrightTestScript, 'playwright')
    
    if (result.success) {
      importedSteps.value = [...scriptStore.steps]
      
      testResults.value.import = {
        title: 'Playwright脚本导入成功',
        type: 'success',
        description: `成功导入 ${scriptStore.stepCount} 个步骤`
      }
      
      addLog(`Playwright脚本导入成功，共 ${scriptStore.stepCount} 个步骤`, 'success')
      ElMessage.success('Playwright脚本导入成功')
    } else {
      throw new Error(result.message)
    }
  } catch (error) {
    testResults.value.import = {
      title: 'Playwright脚本导入失败',
      type: 'error',
      description: `导入失败: ${error.message}`
    }
    
    addLog(`Playwright脚本导入失败: ${error.message}`, 'error')
    ElMessage.error('Playwright脚本导入失败')
  } finally {
    testStates.value.playwright = false
  }
}

const testJsonlImport = async () => {
  testStates.value.jsonl = true
  addLog('开始JSONL脚本导入测试', 'info')

  try {
    const result = scriptStore.importScript(jsonlTestScript, 'jsonl')
    
    if (result.success) {
      importedSteps.value = [...scriptStore.steps]
      
      testResults.value.import = {
        title: 'JSONL脚本导入成功',
        type: 'success',
        description: `成功导入 ${scriptStore.stepCount} 个步骤`
      }
      
      addLog(`JSONL脚本导入成功，共 ${scriptStore.stepCount} 个步骤`, 'success')
      ElMessage.success('JSONL脚本导入成功')
    } else {
      throw new Error(result.message)
    }
  } catch (error) {
    testResults.value.import = {
      title: 'JSONL脚本导入失败',
      type: 'error',
      description: `导入失败: ${error.message}`
    }
    
    addLog(`JSONL脚本导入失败: ${error.message}`, 'error')
    ElMessage.error('JSONL脚本导入失败')
  } finally {
    testStates.value.jsonl = false
  }
}

const testStoreIntegration = async () => {
  testStates.value.store = true
  addLog('开始Pinia Store集成测试', 'info')

  try {
    // 测试脚本Store
    addLog('测试Script Store...', 'info')
    const initialStepCount = scriptStore.stepCount
    
    // 测试录制Store
    addLog('测试Recording Store...', 'info')
    recordingStore.setRecordingUrl('https://test.example.com')
    
    // 测试执行Store
    addLog('测试Execution Store...', 'info')
    executionStore.resetExecution()
    
    await new Promise(resolve => setTimeout(resolve, 500))
    
    testResults.value.store = {
      title: 'Pinia Store集成测试通过',
      type: 'success',
      description: '所有Store状态管理正常工作，数据响应式更新正确'
    }
    
    addLog('Pinia Store集成测试完成', 'success')
    ElMessage.success('Store集成测试通过')
  } catch (error) {
    testResults.value.store = {
      title: 'Pinia Store集成测试失败',
      type: 'error',
      description: `测试失败: ${error.message}`
    }
    
    addLog(`Store集成测试失败: ${error.message}`, 'error')
    ElMessage.error('Store集成测试失败')
  } finally {
    testStates.value.store = false
  }
}

const testCompleteWorkflow = async () => {
  testStates.value.workflow = true
  addLog('开始完整工作流程测试', 'info')

  try {
    // 步骤1: 清空状态
    addLog('步骤1: 清空所有状态...', 'info')
    scriptStore.clearSteps()
    recordingStore.resetRecording()
    executionStore.resetExecution()
    
    // 步骤2: 导入测试脚本
    addLog('步骤2: 导入测试脚本...', 'info')
    const importResult = scriptStore.importScript(playwrightTestScript, 'playwright')
    if (!importResult.success) {
      throw new Error('脚本导入失败')
    }
    
    // 步骤3: 测试格式转换
    addLog('步骤3: 测试格式转换...', 'info')
    const exportedJsonl = scriptStore.exportScript('jsonl')
    if (!exportedJsonl) {
      throw new Error('格式转换失败')
    }
    
    // 步骤4: 模拟录制状态更新
    addLog('步骤4: 模拟录制状态更新...', 'info')
    recordingStore.setRecordingUrl('https://test.example.com')
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    testResults.value.workflow = {
      title: '完整工作流程测试通过',
      type: 'success',
      description: '脚本导入、格式转换、状态管理、组件交互等核心功能均正常工作'
    }
    
    addLog('完整工作流程测试完成', 'success')
    ElMessage.success('完整工作流程测试通过')
  } catch (error) {
    testResults.value.workflow = {
      title: '完整工作流程测试失败',
      type: 'error',
      description: `测试失败: ${error.message}`
    }
    
    addLog(`完整工作流程测试失败: ${error.message}`, 'error')
    ElMessage.error('完整工作流程测试失败')
  } finally {
    testStates.value.workflow = false
  }
}

const clearLogs = () => {
  debugLogs.value = []
  addLog('调试日志已清空', 'info')
}

const getLogClass = (type) => {
  const colors = {
    info: 'text-blue-600',
    success: 'text-green-600',
    error: 'text-red-600',
    warning: 'text-yellow-600'
  }
  return colors[type] || colors.info
}

// 生命周期
onMounted(() => {
  addLog('调试页面已加载', 'success')
  addLog('可以开始测试ScriptVue功能', 'info')
})
</script>

<style scoped>
.debug-card {
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.debug-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.result-display {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.log-entry {
  padding: 2px 0;
  transition: all 0.2s ease;
}

.log-entry:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.log-timestamp {
  font-size: 11px;
}

.log-level {
  font-size: 11px;
}

.log-message {
  font-size: 12px;
}
</style>
